#include "spi_soft.h"

SPI_SOFT_U8 spi_soft_init(spi_soft_node_t *node)
{
    if(node->cpha_mode > 1)
    {
        return 1;
    }
    if(node->cpol_mode > 1)
    {
        return 2;
    }
    if(node->delay_func == NULL)
    {
        return 3;
    }
    if(node->sck_func == NULL)
    {
        return 4;
    }
    if(node->mosi_func == NULL)
    {
        return 5;
    }
    if(node->ss_func == NULL)
    {
        return 6;
    }
    node->ss_func(1);
    node->sck_func(node->cpol_mode);
    return 0;
}

void spi_soft_ss_set(spi_soft_node_t *node, SPI_SOFT_U8 mode)
{
    if(mode == 0)
    {
        node->ss_func(node->cpol_mode);
        node->ss_func(0);
        node->delay_func(DELAY_TICKS);
    }else
    {
        node->ss_func(node->cpol_mode);
        node->ss_func(1);
        node->delay_func(DELAY_TICKS);
    }
}

SPI_SOFT_U8 spi_soft_byte_CTRC(spi_soft_node_t *node, SPI_SOFT_U8 data)
{
    SPI_SOFT_U8 i,ret = 0x00;
    for(i = 0; i < 8; i++)
    {
        node->mosi_func((data & 0x80) == 0 ? 0 : 1);
        data <<= 1;
        node->delay_func(DELAY_TICKS);
        node->sck_func(!(node->cpol_mode));
        node->delay_func(DELAY_TICKS);
        ret <<= 1;
        if(node->miso_func != NULL && node->cpha_mode == 0)
        {
            ret |= ((node->miso_func() == 0) ? 0x00 : 0x01);
        } 
        node->sck_func(node->cpol_mode);
        node->delay_func(DELAY_TICKS);
        if(node->miso_func != NULL && node->cpha_mode == 1)
        {
            ret |= ((node->miso_func() == 0) ? 0x00 : 0x01);
        }
    }
    return ret;
}